import { getCookie } from "@/utils/auth.js";
let webSock = null;
let global_callback = [];
let isConnect = false; // 连接标识，避免重复连接
let recTimer = null; // 断线重连
let isActiveClose = false; // 是否主动连关闭
let wsUri = "";
function createWebSocket() {
  if (window.$config.apiBaseUrl.includes("https")) {
    wsUri = window.$config.apiBaseUrl.replace("https://", "wss://");
  } else {
    wsUri = window.$config.apiBaseUrl.replace("http://", "ws://");
  }
  if (
    webSock === null ||
    Object.prototype.toString.call(webSock) !== "[object WebSocket]"
  ) {
    initWebSocket();
  }
}
function initWebSocket() {
  //   初始化
  const token = getCookie("token");
  webSock = new WebSocket(`${wsUri}/ws/connect/${token}`);
  webSock.onopen = function () {
    // 打开ws
    websocketOpen();
  };
  webSock.onmessage = function (e) {
    websocketOnMsg(e);
  };
  webSock.onclose = function (e) {
    websocketClose(e);
  };
  webSock.onerror = function () {
    websocketError();
  };
}

// 心跳设置
const heartCheck = {
  heartBeatSecond: 10000, // 10s发送一次心跳包
  autoTimer: null, // 延迟发送消息对象，启动心跳新建这个对象，收到消息后重置对象
  autoSend: false,
  start: function () {
    if (this.autoSend === true) {
      this.autoSend = false;
      clearInterval(this.autoTimer);
    } else {
      this.autoSend = true;
      this.autoTimer = setInterval(function () {
        if (isConnect) webSock.send("ping");
        else this.reset();
      }, this.heartBeatSecond);
    }
  },
  reset: function () {
    this.autoTimer && clearTimeout(this.autoTimer);
  }
};
// 重连
function reConnect() {
  recTimer && clearTimeout(recTimer);
  recTimer = setTimeout(() => {
    // 延迟5s重连，避免频繁多次重连请求
    if (!isConnect) {
      initWebSocket();
    }
  }, 5000);
}
// 注册消息回调
function registerCallBack(callback) {
  if (callback && !global_callback.find(func => func === callback)) {
    global_callback.push(callback);
  }
}
// 重置消息回调
function removeCallBack(callBack) {
  global_callback = global_callback.filter(func => func !== callBack);
}
// 发送socket
function sendSocket(agentData) {
  if (!webSock) {
    // 还没创建等1s再继续发送
    setTimeout(() => {
      sendSocket(agentData);
    }, 500);
  } else if (webSock.readyState === webSock.OPEN) {
    // 开启状态则直接发送
    websocketSend(agentData);
  } else {
    // 正在开启状态/未开启状态 1s后重连
    setTimeout(() => {
      sendSocket(agentData);
    }, 500);
  }
}

// 关闭socket
function closeSocket({ activeClose = false }) {
  isActiveClose = activeClose;
  // 清除心跳机制
  heartCheck.reset();
  // 清除重连定时器
  recTimer && clearTimeout(recTimer);
  if (isActiveClose && webSock) {
    // 关闭socket
    webSock.close();
  }
  // 初始化变量
  webSock = null;
  isConnect = false;
}
// 数据发送
function websocketSend(agentData) {
  webSock.send(agentData);
}
// 关闭socket
function websocketClose() {
  // 防止死循环
  if (isActiveClose) {
    isActiveClose = false;
    return;
  }
  closeSocket({ activeClose: true });
}

// 数据接收
function websocketOnMsg(msg) {
  if (!msg || (msg.data && JSON.parse(msg.data).code !== 200)) {
    return;
  }
  const result = JSON.parse(msg.data);
  // result.data ? result.data.chg = 22 : ''; //测试数据更改
  try {
    global_callback.forEach(callback => callback(result.data));
    // eslint-disable-next-line no-unused-vars
  } catch (e) {}
}
function websocketOpen() {
  isConnect = true;
  heartCheck.start(); // 发送心跳
}
function websocketError() {
  // 关闭 重连
  closeSocket({ activeClose: false });
  reConnect();
}
export {
  sendSocket,
  createWebSocket,
  closeSocket,
  removeCallBack,
  registerCallBack
};
